package edu.pmfbl.mnr.sem.mcmatm.beans;

import java.awt.event.*;
import javax.swing.*;

import com.borland.dbswing.*;
import com.borland.dx.dataset.*;

/**
 * <p>Title: MCMA Test Maker</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2009</p>
 *
 * <p>Company: KrndijaSoft</p>
 *
 * @author Ninoslav Krndija
 * @version 1.0
 */
public class JdbMyNavToolBar extends JdbNavToolBar
{
  private boolean dataSetEventsEnabled = true;

  public JdbMyNavToolBar()
  {
    super();
    try {
      jbInit();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  public void jbInit() throws Exception
  {
    getFirstButton().setToolTipText("Prvo pitanje");
    getPriorButton().setToolTipText("Prethodno pitanje");
    getNextButton().setToolTipText("Sledeće pitanje");
    getLastButton().setToolTipText("Poslednje pitanje");
    getInsertButton().setToolTipText("Novo pitanje");
    getDeleteButton().setToolTipText("Briši pitanje");
    getPostButton().setToolTipText("Sačuvaj promjene");
    getCancelButton().setToolTipText("Odustani od promjena");
  }

  /**
   * Updates each button's enabled state based on the state of the
   * currently focused DataSet.
   */
  private void updateButtonEnabledState() {
    try {
      if (getFocusedDataSet() != null && getFocusedDataSet().isOpen())
      {
        boolean readOnly = false;
        if (getFocusedDataSet() instanceof StorageDataSet) {
          readOnly = ((StorageDataSet) getFocusedDataSet()).isReadOnly();
        }
        if (!(getButtonStateFirst() == ENABLED || getButtonStateFirst() == DISABLED)) {
          getFirstButton().setEnabled(!(getFocusedDataSet().atFirst() || getFocusedDataSet().isEmpty()));
        }
        if (!(getButtonStatePrior() == ENABLED || getButtonStatePrior() == DISABLED)) {
          getPriorButton().setEnabled(!(getFocusedDataSet().atFirst() || getFocusedDataSet().isEmpty()));
        }

        if (!(getButtonStateNext() == ENABLED || getButtonStateNext() == DISABLED)) {
          getNextButton().setEnabled(!(getFocusedDataSet().atLast() || getFocusedDataSet().isEmpty()));
        }
        if (!(getButtonStateLast() == ENABLED || getButtonStateLast() == DISABLED)) {
          getLastButton().setEnabled(!(getFocusedDataSet().atLast() || getFocusedDataSet().isEmpty()));
        }

        if (!(getButtonStateInsert() == ENABLED || getButtonStateInsert() == DISABLED)) {
          getInsertButton().setEnabled(getFocusedDataSet().isEnableInsert() && !getFocusedDataSet().isEditingNewRow() && getFocusedDataSet().isEditable() && !readOnly);
        }

        if (!(getButtonStateDelete() == ENABLED || getButtonStateDelete() == DISABLED)) {
          getDeleteButton().setEnabled(getFocusedDataSet().isEnableDelete() && !getFocusedDataSet().isEmpty() && getFocusedDataSet().isEditable() && !readOnly);
        }

        if (!(getButtonStatePost() == ENABLED || getButtonStatePost() == DISABLED)) {
          getPostButton().setEnabled(getFocusedDataSet().isEditing());
        }
        if (!(getButtonStateCancel() == ENABLED || getButtonStateCancel() == DISABLED)) {
          getCancelButton().setEnabled(getFocusedDataSet().isEditing());
        }

        if (!(getButtonStateDitto() == ENABLED || getButtonStateDitto() == DISABLED)) {
          getDittoButton().setEnabled(getFocusedDataSet().isEditingNewRow() || !getFocusedDataSet().isEditing());
        }

        if (!(getButtonStateSave() == ENABLED || getButtonStateSave() == DISABLED)) {
          getSaveButton().setEnabled(getFocusedDataSet().saveChangesSupported() && getFocusedDataSet().isEditable() && !readOnly);
        }
        if (!(getButtonStateRefresh() == ENABLED || getButtonStateRefresh() == DISABLED)) {
          getRefreshButton().setEnabled(getFocusedDataSet().refreshSupported());
        }
      }
      else {
        getFirstButton().setEnabled(false);
        getPriorButton().setEnabled(false);
        getNextButton().setEnabled(false);
        getLastButton().setEnabled(false);
        getInsertButton().setEnabled(false);
        getDeleteButton().setEnabled(false);
        getPostButton().setEnabled(false);
        getCancelButton().setEnabled(false);
        getDittoButton().setEnabled(false);
        getSaveButton().setEnabled(false);
        getRefreshButton().setEnabled(false);
      }
    }
    catch (DataSetException e) {
      DBExceptionHandler.handleException(getDataSet(), e);
    }
  }

  /**
   * Updates each button according to its state (AUTO_ENABLED, AUTO_HIDDEN,
   * ENABLED, DISABLED, HIDDEN).
   */
  private void revalidateButtons() {
    updateButton(getFirstButton(), getButtonStateFirst());
    updateButton(getPriorButton(), getButtonStatePrior());
    updateButton(getNextButton(), getButtonStateNext());
    updateButton(getLastButton(), getButtonStateLast());
    updateButton(getInsertButton(), getButtonStateInsert());
    updateButton(getDeleteButton(), getButtonStateDelete());
    updateButton(getPostButton(), getButtonStatePost());
    updateButton(getCancelButton(), getButtonStateCancel());
    updateButton(getDittoButton(), getButtonStateDitto());
    updateButton(getSaveButton(), getButtonStateSave());
    updateButton(getRefreshButton(), getButtonStateRefresh());
    revalidate();
    repaint();
  }

  private void updateButton(JButton button, int state) {
    switch (state) {
    case AUTO_HIDDEN:
      // Button is only visible if enabled.  If disabled, button is hidden
      if (button.isEnabled()) {
        if (!button.isVisible()) {
          button.setVisible(true);
        }
      }
      else {
        if (button.isVisible()) {
          button.setVisible(false);
        }
      }
      break;
    case ENABLED:
    case DISABLED:
      // Button should be visible and enabled or disabled
      if (!button.isVisible()) {
        button.setVisible(true);
      }
      button.setEnabled(state == ENABLED);
      break;
    case HIDDEN:
      // Button should be hidden (may be enabled or disabled)
      if (button.isVisible()) {
        button.setVisible(false);
      }
      break;
    case AUTO_ENABLED:
    default:
      // Button is always visible, but may be enabled or disabled
      if (!button.isVisible()) {
        button.setVisible(true);
      }
      break;
    }
  }

  // AccessListener implementation
  public void accessChange(AccessEvent event)
  {
    if(event.getID() == AccessEvent.OPEN)  //&& event.getReason() == AccessEvent.DATA_CHANGE) {
      dataSetEventsEnabled = true;
    if(event.getID() == AccessEvent.CLOSE && event.getReason() == AccessEvent.STRUCTURE_CHANGE)
    {
      dataSetEventsEnabled = false;
      return;
    }
    updateButtonEnabledState();
    revalidateButtons();
  }

  // StatusListener implementation
  public void statusMessage(StatusEvent event)
  {
    if(!dataSetEventsEnabled)
      return;
    switch (event.getCode())
    {
      case (StatusEvent.EDIT_STARTED):
      case (StatusEvent.EDIT_CANCELED):
      case (StatusEvent.LOCATE_MATCH_FOUND):
      case (StatusEvent.LOCATE_MATCH_NOT_FOUND):
      case (StatusEvent.DATA_CHANGE):
        updateButtonEnabledState();
        revalidateButtons();
        break;
    }
  }

  // NavigationListener implementation
  public void navigated(NavigationEvent event)
  {
    if(!dataSetEventsEnabled)
      return;
    updateButtonEnabledState();
    revalidateButtons();
  }

  // ActionListener implementation

  public void actionPerformed(ActionEvent e)
  {
    if (getFocusedDataSet() != null)
    {
      try
      {
        JButton button = (JButton) e.getSource();
        if (button == getFirstButton()) {
          getFocusedDataSet().first();
        }
        else if (button == getNextButton()) {
          getFocusedDataSet().next();
        }
        else if (button == getPriorButton()) {
          getFocusedDataSet().prior();
        }
        else if (button == getLastButton()) {
          getFocusedDataSet().last();
        }
        else if (button == getInsertButton()) {
          getFocusedDataSet().insertRow(false);  // INFO Mozda staviti true
        }
        else if (button == getDeleteButton()) {
          getFocusedDataSet().deleteRow();
        }
        else if (button == getPostButton()) {
          getFocusedDataSet().post();
        }
        else if (button == getDittoButton()) {
          getFocusedDataSet().dittoRow(false, true);
        }
        else if (button == getCancelButton()) {
          if (getFocusedDataSet().isEditing()) {
            getFocusedDataSet().cancel();
          }
        }
        else if (button == getSaveButton()) {
          getFocusedDataSet().saveChanges();
        }
        else if (button == getRefreshButton()) {
          getFocusedDataSet().refresh();
        }
      }
      catch (DataSetException ex) {
        DBExceptionHandler.handleException(getDataSet(), ex);
      }
    }
  }

}
